package com.rock.code.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;


public class HttpRequestUtils {
	private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); //日志记录

	/**
	 * httpPost
	 *
	 * @param url 路径
	 * @param jsonParam 参数
	 * @return
	 */
	public static JSONObject httpPost(String url, JSONObject jsonParam) {
		return httpPost(url, jsonParam, false,false);
	}


	/**
	 * @Author zhangli
	 * @Description //TODO
	 * @Date 16:51 2019/2/19
	 * @Param [url, jsonParam, noNeedResponse, isLongConnection] url = zabbix 地址，jsonParm=zabbix参数， noNeedResponse= 是否需要返回值，isLongConnection = true 长连接，其它短链接
	 * @return com.alibaba.fastjson.JSONObject
	 **/
	public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse,boolean isLongConnection) {
		//post请求返回结果
		DefaultHttpClient httpClient = new DefaultHttpClient();
		JSONObject jsonResult = null;
		HttpPost method = new HttpPost(url);
		if(isLongConnection){//长连接
			method.setProtocolVersion(HttpVersion.HTTP_1_1);
			method.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
		}else {//短连接
			method.setProtocolVersion(HttpVersion.HTTP_1_0);
			method.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
		}
		try {
			if (null != jsonParam) {
				//解决中文乱码问题
				StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}
			HttpResponse result = httpClient.execute(method);
			url = URLDecoder.decode(url, "UTF-8");
			/** 请求发送成功，并得到响应 **/
			if (result.getStatusLine().getStatusCode() == 200) {
				String str = "";
				try {
					/** 读取服务器返回过来的json字符串数据 **/
					str = EntityUtils.toString(result.getEntity());
					if (noNeedResponse) {
						return null;
					}
					/** 把json字符串转换成json对象 **/
					jsonResult = JSONObject.parseObject(str);
				} catch (Exception e) {
					logger.error("post请求提交失败:" + url, e);
				}
			}
		} catch (IOException e) {
			logger.error("post请求提交失败:" + url, e);
		}
		return jsonResult;
	}

	/***
	 * @Author zhangli
	 * @Description //TODO //TODO http短连接方式获取post请求,天津header 部分
	 * @Date 11:46 2019/10/15
	 * @Param [url, json, headers]
	 * @return com.alibaba.fastjson.JSONObject
	 **/
	public static JSONObject httpPostHeaderV1(String url, JSONObject json,String headers) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		//尝试使用短连接
		post.setProtocolVersion(HttpVersion.HTTP_1_1);
		post.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);

		if(StringUtils.isNotBlank(headers)){
			String []hs = headers.split("&");
			if(hs.length>0){
				for (String kv : hs) {
					String header_value[] = kv.split("=");
					post.addHeader(header_value[0], header_value[1]);
				}
			}
		}

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
		post.setConfig(requestConfig);
		JSONObject response = null;

		StringEntity s = new StringEntity(json.toString());
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json");//发送json数据需要设置contentType
		post.setEntity(s);
		HttpResponse res = httpClient.execute(post);
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String result = EntityUtils.toString(res.getEntity());// 返回json格式：
			response = JSONObject.parseObject(result);
		}

		return response;
	}

		/***
         * @Author zhangli
         * @Description //TODO http短连接方式获取post请求
         * @Date 10:24 2019/2/16
         * @Param [url, json]
         * @return com.alibaba.fastjson.JSONObject
         **/
	public static JSONObject httpPostV2(String url, JSONObject json) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		//尝试使用短连接
		post.setProtocolVersion(HttpVersion.HTTP_1_1);
		post.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
		post.setConfig(requestConfig);
		JSONObject response = null;

		StringEntity s = new StringEntity(json.toString());
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json");//发送json数据需要设置contentType
		post.setEntity(s);
		HttpResponse res = httpClient.execute(post);
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String result = EntityUtils.toString(res.getEntity());// 返回json格式：
			response = JSONObject.parseObject(result);
		}

		return response;
	}
	/***
	 * @Author zhangli
	 * @Description //TODO http长连接方式获取post请求
	 * @Date 10:24 2019/2/16
	 * @Param [url, json]
	 * @return com.alibaba.fastjson.JSONObject
	 **/
	public static JSONObject httpPostV3(String url, JSONObject json) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		//尝试使用长连接
		post.setProtocolVersion(HttpVersion.HTTP_1_1);
		post.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000).build();
		post.setConfig(requestConfig);
		JSONObject response = null;

		StringEntity s = new StringEntity(json.toString());
		s.setContentEncoding("UTF-8");
		s.setContentType("application/json");//发送json数据需要设置contentType
		post.setEntity(s);
		HttpResponse res = httpClient.execute(post);
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String result = EntityUtils.toString(res.getEntity());// 返回json格式：
			response = JSONObject.parseObject(result);
		}

		return response;
	}

	/**
	 * 发送get请求
	 *
	 * @param url 路径
	 * @return
	 */
	public static JSONObject httpGet(String url) {
		//get请求返回结果
		JSONObject jsonResult = null;
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			//发送get请求
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			/** 请求发送成功，并得到响应 **/
			if (response.getStatusLine().getStatusCode() == 200) {
				/** 读取服务器返回过来的json字符串数据 **/
				String strResult = EntityUtils.toString(response.getEntity());
				/** 把json字符串转换成json对象 **/
				jsonResult = JSONObject.parseObject(strResult);
				url = URLDecoder.decode(url, "UTF-8");
			} else {
				logger.error("get请求提交失败:" + url);
			}
		} catch (IOException e) {
			logger.error("get请求提交失败:" + url, e);
		}
		return jsonResult;
	}
    
    /**
     * 带身份验证的 Get 请求
     * 用于调用华3网管接口
     */
    public static JSONObject httpGet(String url, String ip, int port, String user, String pwd) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(ip, port, "iMC RESTful Web Services"),
                    new UsernamePasswordCredentials(user, pwd));
            //发送get请求
            HttpGet request = new HttpGet(url);
            request.addHeader("accept", "application/json");
            HttpResponse response = client.execute(request);
            
            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == 200) {
                /** 读取服务器返回过来的json字符串数据 **/
                String strResult = EntityUtils.toString(response.getEntity(), "utf-8");
                /** 把json字符串转换成json对象 **/
                jsonResult = JSONObject.parseObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:"+url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:"+url, e);
        }
        return jsonResult;
    }
	
	/**
	 * 带身份验证的 Get 请求
	 * 用于调用华3网管接口
	 * 查询消息头中的属性
	 * @param name 消息头中的属性名
	 */
	public static String httpHeaderGet(String name, String url, String ip, int port, String user, String pwd) {
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            client.getCredentialsProvider().setCredentials(new AuthScope(ip, port), new UsernamePasswordCredentials(user, pwd));
            //发送get请求
            HttpGet request = new HttpGet(url);
            request.addHeader("accept", "application/json");
            HttpResponse response = client.execute(request);
            
            // 请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == 200) {
                // 消息头中有Total属性
                if (response.containsHeader(name)) {
                    Header[] hs = response.getHeaders(name);
                    return hs[0].getValue();
                }
                url = URLDecoder.decode(url, "UTF-8");
            } else {
                logger.error("get请求提交失败:"+url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:"+url, e);
        }
        return null;
    }
	
	public static void main(String[] args) {
		//String url = "http://172.21.148.144:8081/shopping_rest/rest/recharge/getBusiPie.json";
		String url = "http://172.21.148.104:8081/shopping_rest/rest/alarm/getSingleAlarm.json";
		HashMap<String, String> param =new HashMap<String, String>();
		param.put("EVENT_ID", "FB27B8D7E6ACC7BE6C05F341CDA1A13A");
		//System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>"+httpPost(url,param,true));
	}
}